<template>
	<div class="exercises-test exercises-test-preview" v-loading.fullscreen.lock="loading"
		element-loading-text="拼命加载中">
        <el-row class="preview-head" type="flex" align="middle">
            <el-col :span="2" :offset="1">
                <router-link to="/exercises/volume-library"><el-button type="text"><i class="el-icon-arrow-left"></i>返回卷库</el-button></router-link>
            </el-col>
        </el-row>
		<div class="preview-conten maxW">
			
			<div class="preview-conten-l">
				
				<div class="preview-conten-l-h">
					<h3>{{testList.name}}</h3>
					<!-- <p>考试时间：120分钟，满分{{this.totalScore}}分</p> -->
					<!-- <p>满分{{totalScore}}分</p> -->
					<p>考试时间：{{testList.answer_time ? testList.answer_time : '--'}}分钟，满分{{totalScore}}分</p>
				</div>


				<ul>
					<template v-for="type of testList.question_type" >
						<li class="preview-conten-list" :key="type.id">
							
							<!-- <div class="preview-conten-title" v-if="type.id == 1">
								{{type.cn_num}}. {{type.question_type}} (本类题共{{type.count}}小题，每小题{{type.score/type.count}}分，共{{type.score}}分，每小题备选答案中，只有一个符合题意的正确答案。错选，不选均不得分。)
							</div>

							<div class="preview-conten-title"  v-else-if="type.id == 2">
								{{type.cn_num}}. {{type.question_type}} (本类题共{{type.count}}小题，每小题{{type.score/type.count}}分，共{{type.score}}分，每小题备选答案中，有两个或两个以上符合题意的正确答案。多选、少选、错选、不选均不得分。)
							</div>

							<div class="preview-conten-title"  v-else-if="type.id == 9">
								{{type.cn_num}}. {{type.question_type}} (本类题共{{type.count}}小题，每小题{{type.score/type.count}}分，共{{type.score}}分，每小题备选答案中，两个答案中只有一个符合题意的正确答案。)
							</div>
							<div class="preview-conten-title"  v-else>
								{{type.cn_num}}. {{type.question_type}} (本类题共{{type.count}}小题，每小题{{type.score/type.count}}分，共{{type.score}}分，点击文本框，直接在文本框内作答即可。)
							</div> -->

							<div class="preview-conten-title" >
								{{type.cn_num}}. {{type.question_type}} (本类题共{{type.count}}小题，共{{type.score}}分<span v-show="type.common">，{{type.common}}。</span>)
							</div>

							<ul class="preview-conten-subject">

								<template v-for="(item, index) of testList.question_list" v-if="parseInt(item.qt_id) === parseInt(type.id)">

								
									<li :id="item.id" class="preview-conten-subject-c"  v-if="parseInt(item.type_base_id) === 1 ||  parseInt(item.type_base_id) === 2 || parseInt(item.type_base_id) === 4"  :key="index">
										<i v-if="answerList[item.id].score != 0" class="el-icon-check exercises-test-result"></i>
										<i v-else class="el-icon-close exercises-test-result"></i>
		
										<template>
											<div  v-if="item.pattern == 1" class="preview-conten-subject-t">
												<i>{{index+1}}. </i>
												<span v-html="item.content"></span>
												<strong>({{item.score}}分)</strong>
											</div>
											<div  v-if="item.pattern == 2" class="preview-conten-subject-t">
												<i>{{index+1}}. </i>
												<span v-html="item.content"></span>
												<strong v-if="item.score">({{item.score}}分)</strong>
											</div>
										</template>

										<ul class="preview-topic" >

											<template v-if="parseInt(item.type_base_id) === 4">
												<li class="preview-subject-title option-checked"  v-for="(option,index2) of item.option" :key="index2">
													<template v-if="!in_array( option.name, answerList[item.id].userAnswer ) && item.answer != null && in_array( option.name, item.answer )">
														<el-checkbox 
														class="d" 
														disabled 
														:checked= 'true'
														:label="option.name">
														</el-checkbox>
													</template>
													<template v-else-if="item.answer != null && in_array( option.name, item.answer )">
														<el-checkbox 
														class="a" 
														disabled 
														:checked= 'true'
														:label="option.name ">
														</el-checkbox>
													</template>
													<template v-else-if="answerList[item.id].answer != null && !in_array( option.name, item.answer ) && in_array( option.name, answerList[item.id].userAnswer )">
														<el-checkbox 
														class="b" 
														disabled 
														:checked= 'true'
														:label="option.name">
														</el-checkbox>
													</template>
													<template v-else>
														<el-checkbox  
														class="c"
														disabled 
														:label="option.name">
														</el-checkbox>
													</template>	
												</li>
											</template>
											<template v-else>
												<template v-if="item.pattern == 1">
													<li class="preview-subject-title option-checked"  v-for="(option,index2) of item.option" :key="index2">
														<template v-if="!in_array( option.name, answerList[item.id].userAnswer ) && item.answer != null && in_array( option.name, item.answer )">
															<el-checkbox 
															class="d" 
															disabled 
															:checked= 'true'
															:label="option.name">
															</el-checkbox>
															<div  v-html="option.value"></div>
														</template>
														<template v-else-if="item.answer != null && in_array( option.name, item.answer )">
															<el-checkbox 
															class="a" 
															disabled 
															:checked= 'true'
															:label="option.name">
															</el-checkbox>
															<div v-html="option.value"></div>
														</template>
														<template v-else-if="answerList[item.id].answer != null && !in_array( option.name, item.answer ) && in_array( option.name, answerList[item.id].userAnswer )">
															<el-checkbox 
															class="b" 
															disabled 
															:checked= 'true'
															:label="option.name">
															</el-checkbox>
															<div  v-html="option.value"></div>
														</template>
														<template v-else>
															<el-checkbox  
															class="c"
															disabled 
															:label="option.name">
															</el-checkbox>
															<div v-html="option.value"></div>
														</template>	
													</li>
												</template>
												<template v-if="item.pattern == 2">
													<li class="preview-subject-title option-checked option-pattern"  v-for="(option,index2) of item.option" :key="index2">
														<template v-if="!in_array( option.name, answerList[item.id].userAnswer ) && item.answer != null && in_array( option.name, item.answer )">
															<el-checkbox 
															class="d" 
															disabled 
															:checked= 'true'
															:label="option.name">
															</el-checkbox>
															<!-- <div  v-html="option.value"></div> -->
														</template>
														<template v-else-if="item.answer != null && in_array( option.name, item.answer )">
															<el-checkbox 
															class="a" 
															disabled 
															:checked= 'true'
															:label="option.name">
															</el-checkbox>
															<!-- <div v-html="option.value"></div> -->
														</template>
														<template v-else-if="answerList[item.id].answer != null && !in_array( option.name, item.answer ) && in_array( option.name, answerList[item.id].answer )">
															<el-checkbox 
															class="b" 
															disabled 
															:checked= 'true'
															:label="option.name">
															</el-checkbox>
															<!-- <div  v-html="option.value"></div> -->
														</template>
														<template v-else>
															<el-checkbox  
															class="c"
															disabled 
															:label="option.name">
															</el-checkbox>
															<!-- <div v-html="option.value"></div> -->
														</template>	
													</li>
												</template>
											</template>
										</ul>

										<el-collapse accordion class="preview-answer" v-if='1'>
											<el-collapse-item>
										
												<template slot="title">
													<div class="preview-accordion-title">
														<span>得分: {{answerList[item.id].score}} </span>
													</div>
													<div class="accordion-operate" @click.stop="">
														<a class="accordion-open" v-if=" $store.getters.userInfo.check_role == 4"   @click.stop="operationTest($event, item, 1)">收藏本题</a>
														<el-button type="primary" v-if="answerList[item.id].score == 0" @click.stop="operationTest($event, item, 2)"><i class="el-icon-plus"></i>添加错题本</el-button>
													</div>
												</template>


												<div class="preview-accordion-answer">
													<span>正确答案： </span>
													<div>
														<i v-for="answer of item.answer">{{answer}}</i>
													</div>
												</div>
												<div class="preview-accordion-answer">
													<span>统计： </span>
													<div>本题共被作答 {{item.question_info.answer_count}} 次，正确率为 {{item.question_info.true_probability}}%</div>
												</div>
												<div class="preview-accordion-answer">
													<span>解析： </span>
													<template v-if="item.pattern == 1">
														<div v-html="item.resolve"></div>
													</template>
													<template v-if="item.pattern == 2">
														<div>
															<img :src="BASE_URL + item.resolve_path">
														</div>
													</template>
												</div>
											</el-collapse-item>
										</el-collapse>
									</li>

									<li :id="item.id" class="preview-conten-subject-c" v-else>
										<!-- <i v-if="isPraise == 0" class="el-icon-time exercises-test-result"></i> -->
										<template>
											<div  v-if="item.pattern === 1" class="preview-conten-subject-t">
												<i>{{index+1}}. </i>
												<span v-html="item.content"></span>
												<strong>({{item.score}}分)</strong>
											</div>
											<div  v-if="item.pattern === 2" class="preview-conten-subject-t">
												<i>{{index+1}}. </i>
												<span v-html="item.content"></span>
												<strong>({{item.score}}分)</strong>
											</div>
										</template>
		
									

										<template>

											<div class="knowledge-answer" v-if="parseInt(item.type_base_id) === 3 ">
												<span>答案</span>
												<template  v-if="answerList.length != 0" >
													<div class="knowledge-html" >
														<div v-for="(answer, num) of answerList[item.id].userAnswer" >
															<i>{{++num }}.</i> 
															<span v-if="answer.answer"> {{answer.answer}}</span>
															<span v-else class="knowledge-html-un"> 未作答</span>
														</div>
													</div>
												</template>
												
												<div class="knowledge-html-un" v-else ><i class="el-icon-warning-outline"></i>未作答</div>
											</div>

											<div class="knowledge-answer" v-else>
												<span>答案</span>
												<div class="knowledge-html" v-if="answerList[item.id].userAnswer != ''" v-html="answerList[item.id].userAnswer"></div>
												<div class="knowledge-html-un" v-else ><i class="el-icon-warning-outline"></i>未作答</div>
											</div>
										</template>
											

										<el-collapse accordion class="preview-answer">
											<el-collapse-item>
												<template slot="title">
													<div class="preview-accordion-title">
														<span>得分: {{answerList[item.id].score}} </span>
													</div>
													<div class="accordion-operate">
														<a class="accordion-open" v-if=" $store.getters.userInfo.check_role == 4"   @click.stop="operationTest($event, item, 1)">收藏本题</a>
														<el-button type="primary" @click.stop="operationTest($event, item, 2)"><i class="el-icon-plus"></i>添加错题本</el-button>
													</div>
												</template>

												<div class="preview-accordion-answer">
													<span>统计： </span>
													<div>本题共被作答 {{item.question_info.answer_count}} 次，正确率为 {{item.question_info.true_probability}}%</div>
												</div>
												<div class="preview-accordion-answer">
													<span>解析： </span>
													<template v-if="item.pattern == 1">
														<div v-html="item.resolve"></div>
													</template>
													<template v-if="item.pattern == 2">
														<div>
															<img :src="BASE_URL + item.resolve_path">
														</div>
													</template>
												</div>
											</el-collapse-item>
										</el-collapse>
									</li>
								</template>

							</ul>
						</li>
					</template>
				</ul>

			</div>

			<div class="exercises-conten-r">

				<div class="exercises-conten-time" v-if="0">
					<div class="exercises-time-countdown">
						<i class="el-icon-time"></i>
						<strong>用时</strong>
						<span>{{testObj.time ? testObj.time : '00:00:00'}}</span>
					</div>
				</div>

				<div class="exercises-rewinding">
					<p>系统改卷</p>
					<ul>
						<li>
							<p>{{answerInfo.count}}</p>
							<p>全部题目</p>
						</li>
						<li>
							<p>{{answerInfo.correct}}</p>
							<p>正确题目</p>
						</li>
						<li>
							<p class="exercises-score">{{answerInfo.score}}</p>
							<p>得分</p>
						</li>
					</ul>
					<p>主观题</p>
					<ul>
						<li>
							<p>{{answerInfo.sum}}</p>
							<p>全部题目</p>
						</li>
						<li>
							<p class="exercises-score">{{answerInfo.score2}}</p>
							<p>得分</p>
						</li>
					</ul>
				</div>

				<ul class="exercises-conten-r-type">

					<template  v-for="(type, list) of questionList" >
						<li class="exercises-conten-r-type-state exercises-result-state">
							<div>{{type.name}}<i>（共{{type.score}}分）</i></div>
							<ul>
								<template  v-for="(item, index) of type.children">
									<li  v-if="parseInt(item.qt_id) == parseInt(type.id)" :key="index" @click="setCheck(item)">
										<input type="checkbox" :name="index" :checked="item.html_default">

										<template v-if=" parseInt(item.type_base_id) != 1 && parseInt(item.type_base_id) != 2  && parseInt(item.type_base_id) != 4">
											<a :href=" '#' + item.id"  class="exercises-praise">{{++index}}</a>
										</template>

										<template v-else-if="parseInt(item.type_base_id) != 1 && parseInt(item.type_base_id) != 2  && parseInt(item.type_base_id) != 4 && answerList[item.id].answer == '' ">
											<a :href=" '#' + item.id" class="exercises-unanswered">{{++index}}</a>
										</template>

										<template v-else>
											<a :href=" '#' + item.id" v-if="item.html_default == 0" class="exercises-unanswered">{{++index}}</a>
											<a :href=" '#' + item.id" v-else-if="item.html_default == 1 " class="exercises-success">{{++index}}</a>
											<a :href=" '#' + item.id" v-else-if="item.html_default == 2" class="exercises-error">{{++index}}</a>
										</template>

									</li>
								</template>

							</ul>
						</li>
					</template>

				</ul>

				
				<div class="exercises-answer-state">
					<span>正确<i></i></span>
					<span>未答<i></i></span>
					<span>错误<i></i></span>
				</div>

			</div>

		</div>

		<!-- 预览图片 -->
		<image-viewer 
            v-if="imagePreview.showViewer"
            :initial-index="imageIndex"
            :on-close="closeViewer"
            :url-list="imagePreview.previewSrcList">
        </image-viewer>

	</div>
</template>

<script>
	
	export default {
		data(){
			return {
				imagePreview: {/*图片预览*/
					showViewer: false,
					previewSrcList: []
				},
				totalScore: 0,
				headClassList: null,

				testList:[],		/* 试卷列表 */
				answerList: [],		/* 试卷答案 */
				questionList: [], 	/*试卷列表*/
				testObj: {
					name: '',
					time: '',
					time2: '',
					score: 0,
					type: 1,
				},
				answerInfo: {
					count: 0,		/*系统改卷-全部题目*/
					score: 0, 		/*系统改卷-正确题目*/
					correct: 0, 	/*系统改卷-得分*/
					sum: 0,			/*主观题--全部题目*/
					score: 0		/*主观题--得分*/
				},

				loading:false,
				imgIndex: 0

			}
		},
		mounted(){
			this.headClassList = document.querySelector('#trunk').classList;
			this.headClassList.add('hidden-header')

			document.querySelector('.preview-conten-l').addEventListener('click',  (e)=> {
				
				let [targetSrc ,imgs, srcArr, currentIdx] = ['', '', '', '']
				if (e.target.nodeName === 'IMG') {

					this.imagePreview.showViewer = true
					targetSrc = e.target.src;
					imgs = [...e.target.parentNode.children];
					srcArr = imgs.map(item=>item.currentSrc);
					currentIdx = srcArr.indexOf(targetSrc);

					this.imagePreview.previewSrcList = srcArr
					this.imgIndex = targetSrc

				}
			
			}, false)
		},
		computed: {
			imageIndex() {
			    return this.imagePreview.previewSrcList.indexOf(this.imgIndex);
			}

		},
		destroyed(){
			this.headClassList.remove('hidden-header')
		},
		created(){
			this.getTestList()
		},
		methods: {
			/**
			 * 关闭图片
			 * @DateTime 2020-04-16T17:40:41+0800
			 * @qiu_m
			 * @return   {[type]}                 [description]
			 */
			 closeViewer() {
			 	this.imagePreview.showViewer = false;
			 	this.imagePreview.previewSrcList = []
			 },
			/**
			 * 重新排序试卷
			 * @DateTime 2019-08-12T09:38:37+0800
			 * @param    {[type]}                 arr   [description]
			 * @return   {[type]}                       [description]
			 */
			 reSort(arr){

			 	return function(a,b){
			 		var value1 = a[arr];
			 		var value2 = b[arr];
			 		return value1 - value2;
			 	}
			 },
			/**
			 * 根据参数请求试卷详情
			 * @DateTime 2019-07-22T17:37:30+0800
			 * @return   {[type]}                 [description]
			 */
			getTestList(){
				let success = (res=>{
					this.testList = res.data;
					// 计算试卷的总分数
					for (let s = 0; s < this.testList.question_type.length; s++) {
						this.totalScore += parseInt(this.testList.question_type[s].score)
					};
					/*根据id大小排序*/
					// this.testList.question_list = this.testList.question_list.sort(this.reSort('qt_id'));
					this.testObj.name = res.data.task_name;

					/*组装一个新的试卷数据*/
					this.questionList = [];
					res.data.question_type.forEach((item)=>{
						this.questionList.push({
							id: item.id,
							count: item.count,
							name: item.question_type,
							score: item.score,
							type: item.cn_num,
							children: []
						});
					})
					let [indexs, scoreSum, correctIndex, keys, scoreSum2] = [0,0,0,0,0]


					/*this.$nextTick(()=>{
						//改变试题 img 的 url
						let imgArr = document.querySelectorAll('.preview-conten-subject-c img')
						let baseUrl = sessionStorage.getItem('host_addr');
						for (var i = 0; i < imgArr.length; i++) {
							let _temp = imgArr[i].src
							imgArr[i].src = _temp.replace(location.protocol+'//'+location.host, baseUrl);
						}
					})*/

					res.data.question_list.forEach((list, key)=>{

						/*选择题的遍历条件*/
						if (list.type_base_id == 1 || list.type_base_id == 2 || list.type_base_id == 9) {
							list.answer = [...list.answer]
							list.option = list.option != null ? [...list.option] : []
							list.test_library_answer.answer = (list.test_library_answer.answer != "" ? JSON.parse(list.test_library_answer.answer) : [])

							let answer = list.answer.join();
							let correctAnswer = list.test_library_answer.answer.join();

							/*遍历正确的题目*/
							if (answer == correctAnswer) {
								this.answerList[list.id] = {
									type: list.type_base_id,
									id: list.id,
									score: list.score,
									answer: list.answer,
									userAnswer: list.test_library_answer.answer
								}
							}else{
								/*遍历不正确的题目*/
								this.answerList[list.id] = {
									type: list.type_base_id,
									id: list.id,
									score: 0,
									answer: list.answer,
									userAnswer: list.test_library_answer.answer
								}
							}
							/*判断题目是否正确*/
							if (this.answerList[list.id].score != 0) {
								list.html_default = 1 /*正确*/
							}else if (this.answerList[list.id].answer.length == 0) {
								list.html_default = 0 /*未答*/
							}else{
								list.html_default = 2 /*错误*/
							}
		
						}else{
							list.test_library_answer.answer = (list.test_library_answer.answer != "" ? JSON.parse(list.test_library_answer.answer) : '')
							/*非选择题的遍历*/
							this.answerList[list.id] = {
								type: list.qt_id,
								id: list.id,
								score: 0,
								answer: list.answer,
								userAnswer: list.test_library_answer.answer
							}
						}

						/*遍历试题*/
						this.questionList.forEach((item, index)=>{
							if (list.qt_id == item.id) {
								item.children.push(list)

							}
						});
					});

					/*计算 系统改卷 & 主观题 的条件*/
					this.answerList.forEach((item)=>{

						/* 系统改卷 */
						if (item.type == 1 || item.type == 2) {
							scoreSum += parseInt(item.score)
							++indexs
							if (parseInt(item.score) > 0) { ++correctIndex}
						}else{
							++keys
							if (this.isPraise == 0) {
								scoreSum2 += parseInt(item.score)
							}
						}
					})

					this.answerInfo.count = indexs;
					this.answerInfo.score = scoreSum;
					this.answerInfo.correct = correctIndex;
					this.answerInfo.sum = keys;
					this.answerInfo.score2 = scoreSum2;

					this.loading = false
				});

				let params = {
					user_id: this.$g.user_id,
					id: this.$route.query.id
				};

				let fail = (res=>{
					this.$message.error({
						duration: 8000,
						message: res.msg
					})
				})

				this.$ajax({
					url: 'api/newtest/test_detail',
					method: 'get',
					params: params,
					func: {success: success, fail: fail}
				})
			},
			/**
			 * 发布任务表单
			 * @return {[type]} [description]
			 */
			setSubmit(){
				this.$confirm('是否开始做卷？', '提示', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning',
					customClass: 'confirm-them',
				}).then(() => {


				}).catch(() => {});
			},

			 /**
			  * 返回上一页
			  * @return {[type]} [description]
			  */
			 goBack(){
				this.$router.back(-1)
			
			 },
			/**
			 * 收藏试题
			 * @return {[type]} [description]
			 */
			operationTest(val , obj, type) {

				switch(type){

					case 1:
						this.$confirm('确定要将该试题收藏到我的题库吗？', '收藏', {
							cancelButtonText: '取消',
							confirmButtonText: '确定',
							type: 'warning',
							customClass: "myHomework"
						}).then(() => {

							let success = (res=>{
								this.$message.success(res.msg)
								this.getTestList()
							})
							let params = {id: obj.id}
							
							this.$ajax.post('api/newtest/fav_test_question', params, {func: {success: success}})
						}).catch(() => {});
					break;
					case 2:
					this.$confirm('确定要将该试题复制一份到我的错题本吗？', '添加错题本', {
						confirmButtonText: '确认',
						cancelButtonText: '取消',
						type: 'warning',
						customClass: 'myHomework',
					}).then(() => {


						let success = (res=>{
							this.$message.success(res.msg)
							this.getTestList()
						})
						let answer = this.answerList.length > 0 ? this.answerList[obj.id].answer : []
						let params = {
							user_id: this.$g.user_id,
							question_id: obj.id,/*试题id*/
							error_answer: answer,/*当前用户的错误回答*/
							// subject_id: '',/*科目id 这个取决于试卷的科目还是试题的科目 得问产品 如果不发 默认题目的科目*/
							
						}
						
						this.$ajax.post('api/newtest/error_question', params, {func: {success: success}})

					}).catch(() => {});
					break;
				}
				
			},
		}
	}
</script>
